import BlockButton from '@/components/BlockButton';
import TabHeader from '@/components/TabHeader';
import TextButton from '@/components/TextButton';
import { AppContext } from '@/store/index.context';
import { ShowGameAthleteInfo } from '@/types/game.page';
import React, { useCallback, useContext, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import RoundResult from './components/RoundResult';
import GameAthletes from './GameAthletes';
import GameResult from './GameResult';
import classes from './index.module.css';

export default function Game() {
  const { gameStore, personStore } = useContext(AppContext);
  const { getRoundInfos, getPositionPersonIds, computeTotalPoints } = gameStore;
  const { getPersonsByIds } = personStore;
  const roundInfos = useMemo(() => getRoundInfos(), [getRoundInfos]);
  const [showGameResult, setShowGameResult] = useState(false);

  const icons = useMemo(
    () => ['icon-diyi', 'icon-second-circle', 'icon-third-circle', 'icon-pig '],
    [],
  );

  const positionPersonIds = useMemo(
    () => getPositionPersonIds() as string[],
    [getPositionPersonIds],
  );

  const positionPersons = useMemo(
    () => getPersonsByIds(positionPersonIds),
    [positionPersonIds, getPersonsByIds],
  );

  const athleteInfos = useMemo(() => {
    const totalPoints = computeTotalPoints();
    console.log('totalPoints', totalPoints);
    const infos: ShowGameAthleteInfo[] = positionPersons.map(
      (person, index) => ({
        name: person?.name || '',
        score: totalPoints[index + 1],
        icon: '',
      }),
    );
    const sortedInfos = [...infos].sort((a, b) => b.score - a.score);
    sortedInfos.forEach((info, index) => {
      info.icon = icons[index];
    });
    return infos;
  }, [positionPersons, computeTotalPoints, icons]);

  const handleCloseGame = useCallback(() => {
    setShowGameResult(true);
  }, []);

  const navigate = useNavigate();
  return (
    <>
      <TabHeader title="比赛信息" />
      <div className={classes.Game}>
        <div className={classes.TopButtons}>
          <TextButton onClick={() => navigate('/round')}>
            添加一局信息
          </TextButton>
          <BlockButton
            onClick={handleCloseGame}
            text="结算分数"
            type="primary"
          />
        </div>
        <GameAthletes infos={athleteInfos} />
        {roundInfos.map(roundInfo => (
          <RoundResult
            roundInfo={roundInfo}
            key={roundInfo.roundId}
            positionPersonIds={positionPersonIds}
          />
        ))}
        <div className={classes.GongTuo}>注：供托会在总计中自动进行计算</div>
        {showGameResult && (
          <GameResult setShowGameResult={setShowGameResult} icons={icons} />
        )}
      </div>
    </>
  );
}
